<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body onload="todolist('all')">
    <div>
    <h1>待办事项清单</h1>
    <input name="name" type="radio" onchange=todolist('0')>未完成项
    <input name="name" type="radio" onchange=todolist('1')>已完成项
    <input name="name" type="radio" onchange=todolist('all') checked="checked">所有项<br/>
    <input type="text"id="text1"placeholder="添加新事项">
    <button onclick="create_todo()">+</button>
    <input type="text" id='list_title' placeholder="删除事项">
    <input type='submit' value="删除" onclick=del_id()>
    <ul id = 'todo_list'>

    </ul>
    </div>

    <script>
        "use script"
        function todolist(completed){
            fetch('/todos'+'?completed='+completed)
            .then(response => response.json())
            .then(data => {
                document.getElementById("todo_list").innerHTML="";
                var data1 = data.todos1;
                console.log(data1);
                for(i= 0;i<data1.length;i++){
                        var opt = '<li><input type="checkbox" name="'+data1[i].id+'"onchange="is_finish(this.name)"><span>'+data1[i].title+'</span></li>'
                        document.getElementById("todo_list").innerHTML += opt;

              }
            })
        }
        function create_todo(){
            var url = '/create';
            var text1 = document.getElementById('text1').value;
            var data = {title: text1};
            fetch(url, { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json' }) })
            todolist('all')
            }
        function is_finish(id){
            fetch('/todos/mark_completed'+'?id='+id)
            .then(res => res.json())
            .then(function(data){
                if ('title' in data){
                    todolist('all');
                }
            })
        }
         function del_id(){
           id = document.getElementById('list_title').value;
           fetch('/todos/del_id'+'?id='+id)
           .then(res=>res.json())
           .then(function(data){
                todolist('all');
           });
           }


        



    </script>
</body>
</html>